﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MAF.Common;

namespace MAF
{
    /// <summary>
    /// 内存数据库
    /// </summary>
    public static class MemoryDB
    {
        /// <summary>
        /// 静态构造方法
        /// </summary>
        static MemoryDB()
        {
            _data = new Dictionary<object, object>();
        }

        /// <summary>
        /// 标识符名字
        /// </summary>
        private const string _identifierName = "Id";

        /// <summary>
        /// 内存持久对象
        /// </summary>
        private static Dictionary<object, object> _data;

        /// <summary>
        /// 添加，修改
        /// </summary>
        /// <param name="o"></param>
        public static void Save(object o)
        {
            if (null == o)
            {
                throw new ArgumentNullException("参数o不能为null");
            }

            var id = ReflectHelper.GetMemberValue<object>(o, _identifierName);
            if (null == id)
            {
                throw new ArgumentException("参数o必须带名为Id的属性，或Id属性值不能为null");
            }

            _data[id] = o;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static bool Delete(object id)
        {
            return _data.Remove(id);
        }

        /// <summary>
        /// 根据Id查找
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public static T GetById<T>(object id)
        {
            object o = null;
            if (_data.ContainsKey(id))
            {
                o = _data[id];
            }
            return o == null ? default(T) : ReflectHelper.DeepClone<T>((T)o);
        }

        /// <summary>
        /// 根据条件查找
        /// </summary>
        /// <param name="qc"></param>
        /// <returns></returns>
        public static List<T> GetByQuery<T>(IQuery qc)
        {
            List<T> list = new List<T>();

            foreach (var kvp in _data)
            {
                if (null == qc || qc.IsMatch(kvp.Value))
                {
                    list.Add(kvp.Value == null ? default(T) : (T)kvp.Value);
                }
            }

            return list;
        }

        /// <summary>
        /// 清除所有数据，一般应该只是单元测试时有用。
        /// </summary>
        public static void Clear()
        {
            _data.Clear();
        }
    }
}
